import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  // 登录页面
  { path: '/Login', name: 'Login', component: () => import('@/views/Login.vue') },
  // 后台界面
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    // 用户管理界面
    redirect: '/Welcome',
    children: [
      { path: '/Welcome', name: 'Welcome', component: () => import('@/views/Welcome.vue') },
      { path: '/users', name: 'users', component: () => import('@/views/user/Users.vue') },
      { path: '/userInfo', name: 'userInfo', component: () => import('@/views/user/UserInfo.vue') },
      // 文章管理界面
      { path: '/articleCate', name: 'articleCate', component: () => import('@/views/article/articleCate.vue') },
      { path: '/articles', name: 'articles', component: () => import('@/views/article/articles.vue') },
      // 权限管理界面
      { path: '/roles', name: 'roles', component: () => import('@/views/power/Roles.vue') },
      { path: '/rights', name: 'rights', component: () => import('@/views/power/Rights.vue') },
      // 商品管理界面
      { path: '/categories', name: 'categories', component: () => import('@/views/goods/Categories.vue') },
      { path: '/params', name: 'params', component: () => import('@/views/goods/Params.vue') },
      { path: '/goods', name: 'goods', component: () => import('@/views/goods/List.vue') },
      { path: '/goods/add', name: 'goodsAdd', component: () => import('@/views/goods/Add.vue') },
      // 订单管理界面
      { path: '/orders', name: 'orders', component: () => import('@/views/order/Order.vue') },
      // 数据统计界面
      { path: '/reports', name: 'reports', component: () => import('@/views/report/Report.vue') }
    ]
  }
]

const router = new VueRouter({
  // mode: 'history',
  // base: '/one',
  routes
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数,表示放行
  //   next()  放行     next('/login') 强制跳转

  // 判断用户是不是访问登录页,是就直接放行
  if (to.path === '/Login') return next()
  // 如果用户访问的不是登录页,那么获取token来判断
  const tokenStr = store.state.userToken
  // 判断 tokenStr 的真是存在性
  if (!tokenStr) return next('/Login')
  next()
})

export default router
